import java.util.HashMap;
import java.util.Map;

/**
 * 560. 和为K的子数组
 */
public class Solution_560 {
    /**
     * 方法四：前缀和 + 哈希表优化
     * <p>
     * 时间复杂度：O(N)
     * <p>
     * 空间复杂度：O(N)
     */
    public int subarraySum(int[] nums, int k) {
        int count = 0, preSum = 0;
        // key：前缀和，value：key 对应的前缀和的个数
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            preSum += nums[i];
            if (map.containsKey(preSum - k)) {
                count += map.get(preSum - k);
            }
            map.put(preSum, map.getOrDefault(preSum, 0) + 1);
        }
        return count;
    }

    /**
     * 方法三：前缀和
     * <p>
     * 时间复杂度：O(N^2)
     * <p>
     * 空间复杂度：O(N)
     */
    public int subarraySum3(int[] nums, int k) {
        int len = nums.length;
        // 计算前缀和
        int[] preSum = new int[len + 1];
        preSum[0] = 0;
        for (int i = 0; i < len; i++) {
            preSum[i + 1] = preSum[i] + nums[i];
        }

        int ans = 0;
        for (int left = 0; left < len; left++) {
            for (int right = left; right < len; right++) {
                if (preSum[right + 1] - preSum[left] == k) {
                    ans++;
                }
            }
        }
        return ans;
    }

    /**
     * 方法二：暴力法优化
     * <p>
     * 时间复杂度：O(N^2)
     * <p>
     * 空间复杂度：O(1)
     */
    public int subarraySum2(int[] nums, int k) {
        int len = nums.length;
        int ans = 0;
        for (int left = 0; left < len; left++) {
            int sum = 0;
            for (int right = left; right < len; right++) {
                sum += nums[right];
                if (sum == k) {
                    ans++;
                }
            }
        }
        return ans;
    }

    /**
     * 方法一：暴力法（超时）
     * <p>
     * 时间复杂度：O(N^3)
     * <p>
     * 空间复杂度：O(1)
     */
    public int subarraySum1(int[] nums, int k) {
        int len = nums.length;
        int ans = 0;
        for (int left = 0; left < len; left++) {
            for (int right = left; right < len; right++) {
                int sum = 0;
                for (int i = left; i <= right; i++) {
                    sum += nums[i];
                }
                if (sum == k) {
                    ans++;
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Solution_560 solution = new Solution_560();
        int[] nums = { 1, 1, 1 };
        int k = 2;
        int ans = solution.subarraySum(nums, k);
        System.out.println(ans);
    }
}
